﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ganaye.EmbeddedDb
{
    public class PendingRecordUpdate : IDisposable
    {
        private Record mRecord;
#if ASSERTS
        string mConstructorStack;
#endif

        public PendingRecordUpdate(Record record)
        {
#if ASSERTS

            mConstructorStack = Environment.StackTrace;
#endif
            System.Diagnostics.Debug.Assert(record.RecordNo != uint.MaxValue, "Invalid RecordNo");
            mRecord = record;
        }

        private void Dispose(bool early)
        {
            if (mRecord == null) return; // double dispose
            if (early)
            {
                mRecord.mTable.mFile.AddRecord(mRecord);
                // handle managed objects
            }
            mRecord.mPendingUpdateCount--;
            mRecord = null;
            // clear 
        }

        void IDisposable.Dispose()
        {
            if (mRecord == null) return; // double dispose
#if ASSERTS
            GC.SuppressFinalize(this);
#endif
            Dispose(true);
        }

#if ASSERTS
        ~PendingRecordUpdate()
        {
            Dispose(false);
            System.Diagnostics.Debug.Assert(false, string.Format("PendingRecordUpdate {0} #{1} was not disposed.\n{1}", 
                mRecord.GetType().Name, 
                mRecord.RecordNo,
                mConstructorStack));
        }
#endif

        public void EndUpdates()
        {
            Dispose(true);
        }

    }
}
